package com.itbour.service.authority.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itbour.com.page.JspPage;
import com.itbour.com.page.Page;
import com.itbour.common.util.StringUtils;
import com.itbour.dao.authority.UserRoleInfoDao;
import com.itbour.dto.authority.OrgRDto;
import com.itbour.dto.authority.RoleDto;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.service.authority.UserRoleInfoService;

public class UserRoleInfoServiceImpl implements UserRoleInfoService {

	private UserRoleInfoDao userRoleInfoDao;

	// 分页获取 角色用户信息
	public Page getUserRoleInfo(Map<String, Object> parm, Integer pageNum,
			Integer pageSize) {
		/*
		 * pageNum 第几页 pageSize 一页几条数据 skipNum 起始位置Limit 0,10; totalSize 总共多少条数据
		 */
		Page page = null;
		int skipNum = JspPage.getStartOfPage(pageNum, pageSize);// 获取起始位置
		int totalSize = userRoleInfoDao.getUserInfCnt(parm);
		while (totalSize > 0 && totalSize <= skipNum) {
			skipNum = skipNum - pageSize;
			pageNum = pageNum - 1;
		}
		// 分页检索
		parm.put("pageSize", pageSize);
		parm.put("skipResults", skipNum);
		List<UserInfoDto> data = userRoleInfoDao.pageGetUserInfo(parm);
		page = new JspPage(skipNum, totalSize, pageSize, data);
		return page;
	}

	public List<RoleDto> getUserRole(Map<String, Object> parm) {
		List<RoleDto> list = new ArrayList<RoleDto>();
		List<RoleDto> list2 = new ArrayList<RoleDto>();
		list = userRoleInfoDao.getRole(parm);
		Integer roleId = userRoleInfoDao.getRoleId(parm);
		if (roleId != null) {
			for (RoleDto roleDto : list) {
				Integer rM = Integer
						.parseInt(roleDto.getRole_meta().toString());
				if ((roleId & rM) > 0) {
					roleDto.setIsChk(2);// 表示选中
				} else {
					roleDto.setIsChk(1);// 表示未选中
				}
				list2.add(roleDto);
			}
		} else {
			for (RoleDto roleDto : list) {
				roleDto.setIsChk(1);
				list2.add(roleDto);
			}
		}
		return list2;
	}

	public void updUserRole(Map<String, Object> parm) {
		List<OrgRDto> result = userRoleInfoDao.getOrgRInfo(parm);
		Integer userId = Integer.parseInt(parm.get("userId").toString());
		String checkId = (String) parm.get("checkId");
		List<Long> list = StringUtils.stringToList2(checkId);
		Long count = 0l;
		for (int i = 0; i < list.size(); i++) {
			count = count + list.get(i);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("role", count);
		map.put("update_by", parm.get("adminId"));
		if (result.size() > 0) {// 修改
			userRoleInfoDao.updOrgRInfo(map);
		} else {// 插入
			userRoleInfoDao.insertOrgRInfo(map);
		}
	}

	public UserRoleInfoDao getUserRoleInfoDao() {
		return userRoleInfoDao;
	}
	public void setUserRoleInfoDao(UserRoleInfoDao userRoleInfoDao) {
		this.userRoleInfoDao = userRoleInfoDao;
	}
}
